#============================================================
#	Rooms
#============================================================
# @datetime: 2022-3-12 14:25:09
#============================================================

class_name Rooms
extends Node2D

const TileSets = preload("res://src/assets/tileset/tileset.tres")

# (按照节点的顺序)
enum Type {
	SIDE	# 侧室
	LR		# 带有左右开口的房间或 LR 房间。
	LRB		# 带有左、右和底部开口的房间或 LRB 房间。
	LRT		# 带有左、右和顶部开口的房间或 LRT 房间。
	LRTB	# 带有左、右、顶部和底部开口的房间或 LRTB 房间。
}

const TileType : Dictionary = {
	Background = INF,	# 背景
	Brick = INF,	# 砖块
	Bridge = INF,	# 桥
	Door = INF,	# 门
	Tree = INF,	# 树
	Home = INF,		# 房间，起始结束门
	Item = INF,	# 物品
	Spikes = INF,	# 尖刺
	Barrel = INF,	# 木桶
	Spring = INF,	# 弹簧
	Stairs = INF,	# 楼梯
	Enemy = INF,	# 敌人
}

const BOTTOM_OPENED := [Type.LRB, Type.LRTB]
const BOTTOM_CLOSED := [Type.LR, Type.LRT]


var room_size := Vector2.ZERO
var cell_size := Vector2.ZERO

var _rng := RandomNumberGenerator.new()



#============================================================
#   Set/Get
#============================================================
func get_room_data(type: int) -> Array:
	# 获取随机一个类型的房间
	var group := get_child(type) as Node2D
	var index := _rng.randi_range(1, group.get_child_count() - 1)
	var room : TileMap = group.get_child(index) as TileMap
	# 所有图块的数据
	var data := []
	for v in room.get_used_cells():
		data.push_back({
			offset = v,
			cell = room.get_cellv(v),
			coord = room.get_cell_autotile_coord(v.x, v.y),
		})
	return data


#============================================================
#   内置
#============================================================
func _notification(what):
	if what == Node.NOTIFICATION_INSTANCED:
		if TileType.Brick == null:
			init_tile_type()
		_rng.randomize()
		# 根据第一个地图设置每个房间的大小
		# 所以所有房间大小要保持一致
		var room := $Side.get_child(0) as TileMap
		room_size = room.get_used_rect().size
		cell_size = room.cell_size


func _init():
	if TileType.Brick == null:
		init_tile_type()


#============================================================
#   自定义
#============================================================
##  需要初始化才能获取 TileType
static func init_tile_type():
	for key in TileType.keys():
		TileType[key] = TileSets.find_tile_by_name(key)



